#include "SettingsManager.h"

#include <cassert>
#include <fstream>
#include <streambuf>
#include <string>

#include <rapidjson/document.h>	// rapidjson's DOM-style API
#include <rapidjson/prettywriter.h>	// for stringify JSON
#include <rapidjson/filestream.h>	// wrapper of C stream for prettywriter as output

#include "utils/MathConstants.h"

SettingsManager::SettingsManager(const std::wstring& configFilePath)
	: mMaxFps(0)
	, mMsPerFrameFloat(0.0f)
	, mMsPerFrameDouble(0.0)
	, mWindowWidth(0)
	, mWindowHeight(0)
{
	// Read file and save its content into a char array
	std::ifstream file;
	file.open(configFilePath.c_str(), std::ifstream::in);
	assert(file.is_open());
	const std::string str((std::istreambuf_iterator<char>(file)), std::istreambuf_iterator<char>());
	file.close();
	
	// Parse json file
	rapidjson::Document document;
	if (document.Parse<0>(str.c_str()).HasParseError()) {
		assert(false);
		return;
	}

	// Fill data with parsed data
	assert(document.HasMember("maxFPS"));
	assert(document["maxFPS"].IsInt());
	mMaxFps = document["maxFPS"].GetInt();
	assert(mMaxFps != 0);

	mMsPerFrameFloat = 1.0f / mMaxFps;
	mMsPerFrameDouble = 1.0 / mMaxFps;

	assert(document.HasMember("windowWidth"));
	assert(document["windowWidth"].IsInt());
	mWindowWidth = document["windowWidth"].GetInt();
	assert(mWindowWidth != 0);

	assert(document.HasMember("windowHeight"));
	assert(document["windowHeight"].IsInt());
	mWindowHeight = document["windowHeight"].GetInt();
	assert(mWindowHeight != 0);
}